package com.wingy.psyduckplayer.Activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wingy.psyduckplayer.R;
import com.wingy.psyduckplayer.http.LrcFileDownload;
import com.wingy.psyduckplayer.model.PropertyBean;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LrcActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
    private TextView tv_lrc;
    private int status;
    private LinearLayout root_Layout;

    //广播接受器
    private StatusChangedReceiver receiver;
    private LinearLayout linearLayout;

    private String lrc_data = null;
    private String fileName = null;
    private String musicName = null;
    private String musicArtist = null;

    private AsyncDownload asyncDownload;
    private GestureDetector gestureDetector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lrc);


        gestureDetector = new GestureDetector(this, this);
        tv_lrc = (TextView) findViewById(R.id.tv_lrc);
        linearLayout = (LinearLayout) findViewById(R.id.lrc_linearLayout);
        bindStausChangedReceiver();
        tv_lrc.setText("当前没有播放歌曲！");
        // 检查状态
        sendBroadcastOnCommand(MusicService.COMMAND_CHECK_IS_PLAYING);
    }


    @Override
    protected void onResume() {
        super.onResume();
        PropertyBean propertyBean = new PropertyBean(LrcActivity.this);
        String theme = propertyBean.getTheme();
        setTheme(theme);
        propertyBean.setAndSaveTheme(theme);
    }

    /**
     * 设置主题
     */
    private void setTheme(String theme) {
        if ("彩色".equals(theme)) {
            linearLayout.setBackgroundResource(R.drawable.bg_color);
        } else if ("花朵".equals(theme)) {
            linearLayout.setBackgroundResource(R.drawable.bg_digit_flower);
        } else if ("群山".equals(theme)) {
            linearLayout.setBackgroundResource(R.drawable.bg_mountain);
        } else if ("小狗".equals(theme)) {
            linearLayout.setBackgroundResource(R.drawable.bg_running_dog);
        } else if ("冰雪".equals(theme)) {
            linearLayout.setBackgroundResource(R.drawable.bg_snow);
        } else if ("女孩".equals(theme)) {
            linearLayout.setBackgroundResource(R.drawable.bg_music_girl);
        } else if ("朦胧".equals(theme)) {
            linearLayout.setBackgroundResource(R.drawable.bg_blur);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
        if (asyncDownload != null && !asyncDownload.isCancelled()) {
            asyncDownload.cancel(true);
        }
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if (e2.getX() - e1.getX() > 150) {
            finish();
            overridePendingTransition(R.anim.to_right_enter, R.anim.to_right_exit);
        }

        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (gestureDetector.onTouchEvent(ev))
            ev.setAction(MotionEvent.ACTION_CANCEL);
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 绑定广播接受器
     */

    private void bindStausChangedReceiver() {
        receiver = new StatusChangedReceiver();
        IntentFilter filter = new IntentFilter(MusicService.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        registerReceiver(receiver, filter);
    }

    private void sendBroadcastOnCommand(int command) {
        Intent intent = new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command", command);
        sendBroadcast(intent);
    }

    private void get_lrc(Context context) throws IOException {
        String[] files = context.fileList();    //本程序内部储存空间的文件列表
        if (musicName != null) {
            fileName = musicName + ".lrc";
            List<String> filelist = Arrays.asList(files);
            if (filelist.contains(fileName)) {   //如果存在本地歌词，直接读出并显示，否则下载歌词
                Log.i("TAG", "has lrc file!");
                String string = drawLrcWord(fileName);
                tv_lrc.setText(string);
            } else {
                ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo info = cwjManager.getActiveNetworkInfo();
                //网络可用则下载
                if (info != null && info.isAvailable()) {
                    Log.i("TAG", "has not lrc file!");
                    asyncDownload = new AsyncDownload();
                    asyncDownload.execute(LrcFileDownload.LRC_SEARCH_URL, musicName);
                } else {
                    Toast.makeText(getApplicationContext(), "当前网路不给力哦，请检测网路配置！", Toast.LENGTH_SHORT).show();
                }
            }
        }

    }

    private String drawLrcWord(String fileName) {
        String lrc_word = "";
        Pattern pattern = Pattern.compile("\\[\\d{2}:\\d{2}.\\d{2}\\]");
        try {
            File file = new File(getApplicationContext().getFilesDir() + "/"
                    + fileName);
            System.out.println(file.getPath());
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line = "";

            while ((line = reader.readLine()) != null) {
                Matcher m = pattern.matcher(line);
                line = m.replaceAll("");
                line = line.replace("[ti:", "");
                line = line.replace("[ar:", "");
                line = line.replace("[al:", "");
                line = line.replace("[by:", "");
                line = line.replace("[i:", "");
                line = line.replace("]", "");
                line = line.contains("offset") ? "" : line;
                line = line.replace("url", "歌词来源");
                line = line.replace("null", "");
                lrc_word += line + "\n";
            }

            return lrc_word;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 内部类，只处理播放状态的广播
     */
    class StatusChangedReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            status = intent.getIntExtra("status", -1);
            switch (status) {
                case MusicService.STATUS_PLAYING:
                    musicArtist = intent.getStringExtra("musicArtist");
                    musicName = intent.getStringExtra("musicName");
                    LrcActivity.this.setTitle("歌词：" + musicName + " " + musicArtist);
                    try {
                        get_lrc(LrcActivity.this);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }

    class AsyncDownload extends AsyncTask<String, Integer, String> {
        //执行时调用该方法
        @Override
        protected String doInBackground(String... strings) {
            String url = null;
            try {
                url = LrcFileDownload.getSongLRCUrl(strings[0], strings[1]);
                lrc_data = LrcFileDownload.getHtmlCode(url);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            return lrc_data;
        }

        //任务执行前执行该方法
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            tv_lrc.setText("搜索歌词中……");
        }

        //任务结束时执行该方法
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s == null) {
                tv_lrc.setText("当前没有歌词");
            } else {
                try {
                    //写入文件
                    FileOutputStream outputStream = LrcActivity.this.openFileOutput(fileName, Context.MODE_PRIVATE);
                    outputStream.write(s.getBytes());
                    outputStream.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String string = drawLrcWord(fileName);
                tv_lrc.setText(string);
            }
        }
    }
}
